package game.utils.sort 
{
	/**
	 * ...
	 * @author Thot
	 */
	public class Radix 
	{
		
		public function Radix() {}
		
		static public function sortInt( p_array:Array ):Array
		{
			var tab:Array = p_array;
			var buckets:Array = null;
			var max:int = p_array.length;
			var i:int = 0;
			var j:int = 0;
			var k:int = 0;
			var l:int = 0;
			var value:int = 0;
			var el:int = 0;
			var curbuck:Array = null;
			var shift:int = 0;
			
			if( p_array.length == 0 )
			{
				return p_array;
			}
			
			l = 0;
			j = 0;
			i = 0;
			
			while( i < 4  )
			{
				buckets = new Array();
				max = tab.length;
				j = 0;
				
				while( j < 512 )
				{
					buckets[j] = new Array();
					j++;
				}
				
				j = 0;
				
				
				while( j < max )
				{
					el = tab[j];
					value = ( el & (255 << (shift)) ) >> (shift);
					value = ( value > 0 ) ? 256 + value : 255 + value;
					buckets[value].push(el);
					j++;
				}
				

				
				j = 0;
				k = 0;
				l = 0;
				
				while( j < 512 )
				{
					curbuck = buckets[j];
					max = curbuck.length;
					
					k = 0;
					while( k < max )
					{
						tab[l] = curbuck[k];
						l++;
						k++;
					}
					j++;
				}
				
				shift+=8;
				i++;
			}
			
			
			
			return tab;
		}
		
		static public function sortByProperty( p_array:Array, p_prop:String ):Array
		{
			var tab:Array = p_array;
			var buckets:Array = null;
			var max:int = p_array.length;
			var i:int = 0;
			var j:int = 0;
			var k:int = 0;
			var l:int = 0;
			var value:int = 0;
			var el:Object = null;
			var curbuck:Array = null;
			
			l = 0;
			j = 0;
			i = 0;
			
			
			if( p_array.length == 0 )
			{
				return p_array;
			}
			
			while( i < 4  )
			{
				
				
				buckets = [];
				max = tab.length;
				j = 0;
				
				while( j < 512 )
				{
					buckets[j] = new Array();
					j++;
				}
				
				j = 0;
				
				
				while( j < max )
				{
					el = tab[j];
					value = ( el[p_prop] & (255 << (i*8)) ) >> (i*8);
					value = ( value > 0 ) ? 256 + value : 255 + value;
					buckets[value].push(el);
					j++;
				}

				
				j = 0;
				k = 0;
				l = 0;
				
				while( j < 512 )
				{
					curbuck = buckets[j];
					max = curbuck.length;
					
					k = 0;
					while( k < max )
					{
						tab[l] = curbuck[k];
						l++;
						k++;
					}
					j++;
				}
				
				i++;
			}
			
			return tab;
		}
		
	}

}

